package ccpp.builder;

import ccpp.bean.Constants;
import ccpp.bean.TableInfo;
import ccpp.utils.PropertiesUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cp
 * @time 2024/4/28 15:45
 * @describe
 */

public class BuildTable {
    private static final Logger logger = LoggerFactory.getLogger(BuildTable.class);
    private static Connection conn = null;

    static {
        String driverName = PropertiesUtils.getProperty("db.driver.name");
        String url = PropertiesUtils.getProperty("db.url");
        String username = PropertiesUtils.getProperty("db.username");
        String password = PropertiesUtils.getProperty("db.password");
        try {
            Class.forName(driverName);
            conn = java.sql.DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException | SQLException e) {
            logger.info("数据库连接失败");
        }
    }

    public static void getTable() {
        PreparedStatement ps = null;
        ResultSet tableResult = null;
        List<TableInfo> tableInfoList = new ArrayList<>();
        try {

            ps = conn.prepareStatement("show table status;");
            tableResult = ps.executeQuery();
            while (tableResult.next()) {
                TableInfo tableInfo = new TableInfo();
                tableInfo.setTableName(tableResult.getString("name"));
                String beanName = tableInfo.getTableName();
                if (Constants.IGNORE_TABLE_PREFIX) {
                    /*
                        忽略以tb_、Tb_、TB_开头的表前缀
                     */
                    if(beanName.startsWith("tb_")||beanName.startsWith("Tb_")||beanName.startsWith("TB_")){
                        beanName = beanName.substring(beanName.indexOf("_") + 1);
                    }
                }
                logger.error("bean {}",beanName);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (tableResult != null) {
                    tableResult.close();
                }
                if (ps != null) {
                    ps.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                logger.error("读取表失败");
            }
        }
    }
}